// cbassistant伪协议安装工具
const process = require("process");
const readline = require("readline");
const path = require("path");
const fs = require("fs");
const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
const INSTALL_COMMANDLINES = [
    'reg add HKEY_CLASSES_ROOT\\cbassistant',
    'reg add "HKEY_CLASSES_ROOT\\cbassistant" /v "URL Protocol" /t REG_SZ /d "{DIR}\\tools\\cbac.bat \\"%%1\\""',
    'reg add "HKEY_CLASSES_ROOT\\cbassistant\\shell\\open\\command" /d "{DIR}\\tools\\cbac.bat \\"%%1\\""'
];
const CBAC = [
    '@echo off',
    'cd {DIR}',
    'node cui cba cb "%1"'
];
const pause = () => rl.question('回车继续', question);

var installer = {
    scriptFile: path.normalize(process.cwd() + "/cui.js"),
    setFile: function () {
        console.clear();
        console.log("------------------------------------------------");
        rl.question('请指定文件:', (answer) => {
            if (answer != "") {
                if (fs.existsSync(answer)) {
                    installer.scriptFile = answer;
                } else {
                    console.error('指定文件不存在!');
                    pause();
                }
            } else {
                question();
            }
        });
    },
    install: function () {
        fs.writeFileSync(process.cwd() + '/tools/cbac.bat', CBAC.join('\n')
            .replace('{DIR}', process.cwd())
            .replace('{SCRIPT}', installer.scriptFile));
        fs.writeFileSync(process.cwd() + '/tools/install_tmp.bat', INSTALL_COMMANDLINES.join('\n')
            .replace('{DIR}', process.cwd())
            .replace('{DIR}', process.cwd()));
        require('child_process').exec(process.cwd() + '/tools/install_tmp.bat');
        console.log('安装完成!');
        pause();
    },
    uninstall: function () {
        require('child_process').exec('reg import "' + process.cwd() + '/tools/removeCBA.reg"');
        console.log('卸载完成!');
        pause();
    }
}

console.log("------------------------CA-CUI cbassistant伪协议安装工具------------------------");
function question() {
    console.clear();
    console.log("e: 退出; i: 安装; u: 卸载; f: 指定脚本文件; \n" +
        "<当前脚本文件> " + installer.scriptFile);
    rl.question(':', (answer) => {
        switch (answer) {
        case 'i':
            installer.install();
            break;
        case 'u':
            installer.uninstall();
            break;
        case 'f':
            installer.setFile();
            break;
        case 'e':
            rl.close();
            process.exit();
            break;
        case 'exit':
            rl.close();
            process.exit();
            break;
        default:
            question();
        }
    });
}
question();
